package org.linlinjava.litemall.web.aop;

import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.web.annotation.repeat.RequestKeyParam;
import org.linlinjava.litemall.web.annotation.repeat.RequestLock;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.types.Expiration;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;
import javax.annotation.Resource;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
@Aspect
@Component
@Slf4j
public class RedisRequestLockAspect {

    @Resource
    private StringRedisTemplate stringredisTemplate;

    @Around("execution(public * * (..)) && @annotation(org.linlinjava.litemall.web.annotation.repeat.RequestLock)")
    public Object interceptor(ProceedingJoinPoint joinPoint){
        Object result;
        //获取连接点的⽅法签名对象
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        //获取方法
        Method method = methodSignature.getMethod();
        //通过方法获取注解的对象
        RequestLock requestLock = method.getAnnotation(RequestLock.class);
        //判断prefix字段不能为空
        if(ObjectUtil.isEmpty(requestLock.prefix())){
            throw new RuntimeException("prefix字段不能为空");
        }
        //获取自定义key，prefix()+添加了RequestKeyParam注解的Field字段，拼接起来
        final String lockKey = getLockKey(joinPoint);
        System.out.println("=========lockKey:" + lockKey);

        //使用redisCallback接口执行set命令，设置锁值
        final Boolean success = stringredisTemplate.execute((RedisCallback<Boolean>) connection ->
                connection.set(lockKey.getBytes(), "repeate".getBytes(),
                        Expiration.from(requestLock.expire(), requestLock.timeUnit()),
                        RedisStringCommands.SetOption.ifAbsent()) //setnx
        );
        if(!success){
//            return ResponseUtil.fail(ORDER_INVALID_OPERATION, "订单不能完成");
            return ResponseUtil.fail(requestLock.message());
        }
        try {
            result = joinPoint.proceed();
        } catch (Throwable e){
            throw new RuntimeException("系统异常");
        }
        return result;
    }


    public String getLockKey(ProceedingJoinPoint joinPoint){
        StringBuilder stringBuilder = new StringBuilder();
        //获取连接点的⽅法签名对象
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        //获取方法对象
        Method method = methodSignature.getMethod();
        System.out.println("=========method:" + method);
        System.out.println("=========method name" + method.getName());
        //获取方法上面注解的对象
        RequestLock requestLock = method.getAnnotation(RequestLock.class);
        //获取方法的参数
        final Object[] args = joinPoint.getArgs();
        for (Object element : args) {
            System.out.println("========args:" + element);
        }

        //获取method对象上的所有注解
        final Parameter[] parameters = method.getParameters();
        System.out.println(parameters.length);
        for (Parameter element : parameters) {
            System.out.println("========parameters:" + element);
        }

        for (int i = 0; i < parameters.length; i++) {
            final RequestKeyParam keyParam = parameters[i].getAnnotation(RequestKeyParam.class);
            //如果属性不是RequestKeyParam注解，则不处理
            if(keyParam == null){
                continue;
            }

            //如果属性是RequestKeyParam注解，则拼接 连接符号 &
            stringBuilder.append(requestLock.delimiter()).append(args[i]);
        }
        System.out.println("==========>stringBuilder拼接有RequestKeyParam注解: " + stringBuilder);

        //注解@RequestKeyParam可以放在方法参数上
        //也可以放在对象的属性上，所以这里要判断两次，一次是获取方法上的注解，一次是获取对象属性里面的注解
        //如果方法上没有加@RequestKeyParam注解
        if(ObjectUtil.isEmpty(stringBuilder.toString())){
            //获取方法上的多个注解
            final Annotation[][] parameterAnnotations = method.getParameterAnnotations();
            //循环注解
            for (int i = 0; i < parameters.length;i++){
                final Object object = args[i];
                //获取注解类所有的属性字段
                final Field[] fields = object.getClass().getDeclaredFields();
                for (Field field : fields) {
                    //判断字段是否有@RequestKeyParam注解
                    final RequestKeyParam annotation = field.getAnnotation(RequestKeyParam.class);
                    //如果没有就跳过
                    if(annotation == null){
                        continue;
                    }
                    //如果有，设置Accessible为true（为true时可以使⽤反射访问私有变量，否则不能访问私有变量）
                    field.setAccessible(true);
                    //如果属性是RequestKeyParam注解，则拼接 连接符" & + RequestKeyParam"
                    stringBuilder.append(requestLock.delimiter()).append(ReflectionUtils.getField(field,
                            object));
                }
            }
        }
        System.out.println("==========>stringBuilder拼接有RequestKeyParam注解: " +
                stringBuilder);

        return requestLock.prefix() + stringBuilder;
    }







}
